import 'dart:io';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../services/exam_service.dart';
import '../data/user_data.dart';
import '../models/exam_model.dart';
import '../models/user_model.dart';
import 'exam_screen.dart';
import 'create_exam_screen.dart';
import 'package:path_provider/path_provider.dart';
import '../services/auth_service.dart';
import 'package:permission_handler/permission_handler.dart';
import '../utils/responsive_util.dart';
import '../services/excel_import_service.dart';
import 'exam_rules_screen.dart';
import '../services/exam_state_service.dart';
import 'result_screen.dart';
import 'student_results_screen.dart';

class ExamListScreen extends StatefulWidget {
  const ExamListScreen({super.key});

  @override
  State<ExamListScreen> createState() => _ExamListScreenState();
}

class _ExamListScreenState extends State<ExamListScreen> {
  late List<Exam> _exams = [];
  bool _isLoading = true;
  User? _currentUser;
  bool _isSearching = false;
  String _searchQuery = '';
  final AuthService _authService = AuthService();
  bool _isAdmin = false;

  @override
  void initState() {
    super.initState();
    _currentUser = UserData.currentUser;
    _checkAdminAccess();
    
    // 请求文件系统权限
    _requestPermissions();
    
    // 加载现有考试
    _loadExistingExams();
  }

  Future<void> _checkAdminAccess() async {
    bool isAdmin = await _authService.isUserAdmin();
    setState(() {
      _isAdmin = isAdmin;
    });
  }

  // 请求必要权限
  Future<void> _requestPermissions() async {
    if (Platform.isAndroid) {
      // Android 需要存储权限
      final status = await Permission.storage.request();
      
      if (status.isPermanentlyDenied) {
        // 用户永久拒绝了权限，提示用户去设置中手动打开
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: const Text('需要存储权限才能读取固定路径的试题文件'),
              action: SnackBarAction(
                label: '设置',
                onPressed: () => openAppSettings(),
              ),
            ),
          );
        }
      }
    }
  }

  // 加载现有考试
  Future<void> _loadExistingExams() async {
    setState(() {
      _isLoading = true;
    });
    
    // 初始化考试服务
    ExamService.init();
    
    // 获取所有考试
    List<Exam> exams = [];
    if (_isAdmin) {
      // 管理员可以看到所有考试
      exams = ExamService.getAllExams();
    } else {
      // 学生只能看到分配给他们的考试，或者尚未分配的考试中的一个
      final studentId = _currentUser?.id ?? '';
      // 尝试获取可用的考试
      final availableExam = ExamService.getAvailableExamForStudent(studentId);
      if (availableExam != null) {
        exams = [availableExam];
      }
    }
    
    setState(() {
      _exams = exams;
      _isLoading = false;
    });
  }

  void _loadExams() {
    // 获取所有考试
    Future.delayed(const Duration(milliseconds: 300), () {
      setState(() {
        _exams = ExamService.getAllExams();
        _isLoading = false;
      });
    });
  }

  void _refreshExams() {
    setState(() {
      _isLoading = true;
    });
    _loadExams();
  }

  List<Exam> get _filteredExams {
    return _exams.where((exam) {
      // 只应用标题搜索过滤
      return _searchQuery.isEmpty ||
          exam.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          exam.description.toLowerCase().contains(_searchQuery.toLowerCase());
    }).toList();
  }

  // 检查当前用户是否有管理权限
  bool get _hasAdminAccess {
    return _currentUser?.id == 'admin001' || _currentUser?.id == 'teacher001';
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: _isSearching 
            ? TextField(
                autofocus: true,
                decoration: InputDecoration(
                  hintText: '搜索考试...',
                  border: InputBorder.none,
                  hintStyle: const TextStyle(color: Colors.white60),
                  contentPadding: EdgeInsets.symmetric(
                    vertical: ResponsiveUtil.scaleHeight(context, 8),
                  ),
                ),
                style: ResponsiveUtil.getBalancedTextStyle(
                  context,
                  fontSize: isTablet ? 18 : 16,
                  color: Colors.white,
                ),
                onChanged: (value) {
                  setState(() {
                    _searchQuery = value;
                  });
                },
              )
            : Text(
                '考试列表',
                style: ResponsiveUtil.getBalancedTextStyle(
                  context,
                  fontSize: isTablet ? 20 : 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
        backgroundColor: Colors.blue.shade800,
        foregroundColor: Colors.white,
        toolbarHeight: ResponsiveUtil.scaleHeight(context, isTablet ? 70 : 60),
        actions: [
          // 搜索按钮
          IconButton(
            icon: Icon(
              _isSearching ? Icons.cancel : Icons.search,
              size: ResponsiveUtil.getIconSize(context),
            ),
            onPressed: () {
              setState(() {
                _isSearching = !_isSearching;
                if (!_isSearching) {
                  _searchQuery = '';
                }
              });
            },
            padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 8)),
            tooltip: _isSearching ? '取消搜索' : '搜索考试',
          ),
          // 刷新按钮
          IconButton(
            icon: Icon(
              Icons.refresh,
              size: ResponsiveUtil.getIconSize(context),
            ),
            onPressed: _refreshExams,
            padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 8)),
            tooltip: '刷新考试列表',
          ),
          // 管理员角色才显示的添加按钮
          if (_isAdmin)
            PopupMenuButton<String>(
              icon: Icon(
                Icons.more_vert,
                size: ResponsiveUtil.getIconSize(context),
              ),
              padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 8)),
              tooltip: '管理员选项',
              itemBuilder: (context) {
                return [
                  PopupMenuItem<String>(
                    value: 'create',
                    child: Row(
                      children: [
                        Icon(Icons.add, color: Colors.green, size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24)),
                        SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                        Text(
                          '新增考试',
                          style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 14),
                        ),
                      ],
                    ),
                  ),
                  PopupMenuItem<String>(
                    value: 'import',
                    child: Row(
                      children: [
                        Icon(Icons.upload_file, color: Colors.blue, size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24)),
                        SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                        Text(
                          '导入Excel',
                          style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 14),
                        ),
                      ],
                    ),
                  ),
                  PopupMenuItem<String>(
                    value: 'template',
                    child: Row(
                      children: [
                        Icon(Icons.download, color: Colors.orange, size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24)),
                        SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                        Text(
                          '下载模板',
                          style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 14),
                        ),
                      ],
                    ),
                  ),
                ];
              },
              onSelected: (value) {
                if (value == 'create') {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const CreateExamScreen(),
                      settings: const RouteSettings(name: 'CreateExamScreen'),
                    ),
                  ).then((_) => _loadExams());
                } else if (value == 'import') {
                  _importExcel();
                } else if (value == 'template') {
                  _downloadTemplate();
                }
              },
            ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _buildExamList(),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.list_alt),
            label: '考试',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle),
            label: '我的',
          ),
        ],
        currentIndex: 1, // 当前在考试列表页
        selectedItemColor: Colors.blue.shade800,
        onTap: (index) {
          // 根据选项导航到不同页面
          if (index == 0) {
            // 导航到首页
            Navigator.pushReplacementNamed(context, '/home');
          } else if (index == 2) {
            // 导航到个人页面 - 可以通过重定向到首页并选择个人标签实现
            Navigator.pushNamedAndRemoveUntil(
              context, 
              '/home', 
              (route) => false,
              arguments: {'initialTab': 2} // 传递参数，表示要选择第三个标签
            );
          }
          // 如果是当前页面(索引为1)，不做任何操作
        },
      ),
    );
  }

  void _navigateToCreateExam() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const CreateExamScreen(),
        settings: const RouteSettings(name: 'CreateExamScreen'),
      ),
    ).then((_) => _refreshExams());
  }

  Future<void> _downloadTemplate() async {
    try {
      // 导出模板
      String? templatePath = await ExamService.exportQuestionTemplate();
      
      if (templatePath != null) {
        // 尝试打开文件
        final file = File(templatePath);
        if (await file.exists()) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: const Text('模板已下载'),
              action: SnackBarAction(
                label: '打开',
                onPressed: () async {
                  final uri = Uri.file(templatePath);
                  if (!await launchUrl(uri)) {
                    if (mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('无法打开文件')),
                      );
                    }
                  }
                },
              ),
            ),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('模板下载失败')),
          );
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('模板下载失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('下载错误: $e')),
      );
    }
  }

  void _showImportExcelDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(
            '导入考试',
            style: ResponsiveUtil.getBalancedTextStyle(
              context,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '请选择要导入考试的方式：',
                style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 16),
              ),
              SizedBox(height: ResponsiveUtil.scaleHeight(context, 20)),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildImportButton(context),
                  SizedBox(width: ResponsiveUtil.scaleWidth(context, 10)),
                  _buildTemplateButton(context),
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              child: Text(
                '取消',
                style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 16),
              ),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
          ),
          contentPadding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 20)),
        );
      },
    );
  }

  // 构建导入Excel按钮
  Widget _buildImportButton(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return ElevatedButton.icon(
      icon: Icon(
        Icons.upload_file,
        size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24),
        color: Colors.white,
      ),
      label: Text(
        '导入Excel',
        style: ResponsiveUtil.getBalancedTextStyle(
          context,
          fontSize: isTablet ? 16 : 14,
          color: Colors.white,
          fontWeight: FontWeight.w500,
        ),
      ),
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.blue,
        padding: EdgeInsets.symmetric(
          horizontal: ResponsiveUtil.scaleWidth(context, isTablet ? 16 : 12),
          vertical: ResponsiveUtil.scaleHeight(context, isTablet ? 12 : 8),
        ),
        minimumSize: Size(
          ResponsiveUtil.scaleWidth(context, isTablet ? 140 : 110),
          ResponsiveUtil.scaleHeight(context, isTablet ? 48 : 40),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        ),
      ),
      onPressed: () => _importExcel(),
    );
  }

  // 构建下载模板按钮
  Widget _buildTemplateButton(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return ElevatedButton.icon(
      icon: Icon(
        Icons.download,
        size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24),
        color: Colors.white,
      ),
      label: Text(
        '下载模板',
        style: ResponsiveUtil.getBalancedTextStyle(
          context,
          fontSize: isTablet ? 16 : 14,
          color: Colors.white,
          fontWeight: FontWeight.w500,
        ),
      ),
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.orange,
        padding: EdgeInsets.symmetric(
          horizontal: ResponsiveUtil.scaleWidth(context, isTablet ? 16 : 12),
          vertical: ResponsiveUtil.scaleHeight(context, isTablet ? 12 : 8),
        ),
        minimumSize: Size(
          ResponsiveUtil.scaleWidth(context, isTablet ? 140 : 110),
          ResponsiveUtil.scaleHeight(context, isTablet ? 48 : 40),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        ),
      ),
      onPressed: () => _downloadTemplate(),
    );
  }

  // 构建新增考试按钮
  Widget _buildAddExamButton(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return ElevatedButton.icon(
      icon: Icon(
        Icons.add,
        size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24),
        color: Colors.white,
      ),
      label: Text(
        '新增考试',
        style: ResponsiveUtil.getBalancedTextStyle(
          context, 
          fontSize: isTablet ? 16 : 14,
          color: Colors.white,
          fontWeight: FontWeight.w500,
        ),
      ),
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.green,
        padding: EdgeInsets.symmetric(
          horizontal: ResponsiveUtil.scaleWidth(context, isTablet ? 16 : 12),
          vertical: ResponsiveUtil.scaleHeight(context, isTablet ? 12 : 8),
        ),
        minimumSize: Size(
          ResponsiveUtil.scaleWidth(context, isTablet ? 140 : 110),
          ResponsiveUtil.scaleHeight(context, isTablet ? 48 : 40),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        ),
      ),
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const CreateExamScreen(),
          ),
        ).then((_) => _loadExams());
      },
    );
  }

  Widget _buildExamList() {
    if (_filteredExams.isEmpty) {
      return const Center(
        child: Text(
          '没有找到考试',
          style: TextStyle(fontSize: 18, color: Colors.grey),
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _filteredExams.length,
      itemBuilder: (context, index) {
        final exam = _filteredExams[index];
        return _buildExamCard(context, exam);
      },
    );
  }

  // 构建考试卡片
  Widget _buildExamCard(BuildContext context, Exam exam) {
    final isTablet = ResponsiveUtil.isTablet(context);
    final cardPadding = ResponsiveUtil.getScaledPadding(
      context, 
      horizontal: isTablet ? 20 : 16, 
      vertical: isTablet ? 16 : 12
    );
    
    return FutureBuilder<ExamStatus>(
      future: ExamStateService.getExamStatus(exam.id, userId: _currentUser?.id),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return _buildStatusBadge('加载中...', Colors.grey);
        }
        
        if (snapshot.hasError) {
          return _buildStatusBadge('错误', Colors.red);
        }
        
        final status = snapshot.data ?? ExamStatus.notStarted;
        
        switch (status) {
          case ExamStatus.completed:
            return _buildStatusBadge('已完成', Colors.green);
          case ExamStatus.inProgress:
            return _buildStatusBadge('进行中', Colors.orange);
          case ExamStatus.notStarted:
            return _buildStatusBadge('未开始', Colors.blue);
        }
      },
    );
  }

  // 获取状态颜色
  Color _getStatusColor(ExamStatus status) {
    switch (status) {
      case ExamStatus.notStarted:
        return Colors.blue;
      case ExamStatus.inProgress:
        return Colors.orange;
      case ExamStatus.completed:
        return Colors.green;
    }
  }
  
  // 获取状态文本
  String _getStatusText(ExamStatus status) {
    switch (status) {
      case ExamStatus.notStarted:
        return '未开始';
      case ExamStatus.inProgress:
        return '进行中';
      case ExamStatus.completed:
        return '已完成';
    }
  }
  
  // 获取状态图标
  IconData _getStatusIcon(ExamStatus status) {
    switch (status) {
      case ExamStatus.notStarted:
        return Icons.play_circle_outline;
      case ExamStatus.inProgress:
        return Icons.pending_outlined;
      case ExamStatus.completed:
        return Icons.check_circle_outline;
    }
  }

  // 构建考试信息项
  Widget _buildInfoItem({
    required BuildContext context, 
    required IconData icon, 
    required String label, 
    required Color color,
  }) {
    final isTablet = ResponsiveUtil.isTablet(context);
    
    return Row(
      children: [
        Icon(
          icon,
          size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24),
          color: color,
        ),
        SizedBox(width: ResponsiveUtil.scaleWidth(context, 4)),
        Text(
          label,
          style: ResponsiveUtil.getBalancedTextStyle(
            context,
            fontSize: isTablet ? 16 : 14,
          ),
        ),
      ],
    );
  }

  // 获取固定路径的示例文件路径并尝试打开
  Future<void> _generateFixedPathTemplate() async {
    try {
      String? templatePath = await ExamService.generateAndSaveTemplate();
      
      if (templatePath != null) {
        final uri = Uri.file(templatePath);
        
        // 显示成功消息和路径
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('试题模板已保存到: $templatePath'),
            duration: const Duration(seconds: 10),
            action: SnackBarAction(
              label: '打开文件夹',
              onPressed: () async {
                try {
                  // 尝试打开文件所在的目录
                  final directory = templatePath.substring(0, templatePath.lastIndexOf('/'));
                  final directoryUri = Uri.directory(directory);
                  if (!await launchUrl(directoryUri)) {
                    throw 'Could not launch $directoryUri';
                  }
                } catch (e) {
                  // 如果无法打开目录，尝试打开文件
                  if (!await launchUrl(uri)) {
                    if (mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('无法打开文件或目录')),
                      );
                    }
                  }
                }
              },
            ),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('无法创建模板文件')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('创建模板错误: $e')),
      );
    }
  }

  // 从固定路径重新加载考试
  Future<void> _reloadFromFixedPath() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 此功能已废弃，提示用户使用Excel导入
      setState(() {
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('此功能已废弃，请使用Excel导入试题')),
      );
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作错误: $e')),
      );
    }
  }

  // 处理考试点击事件
  void _handleExamTap(Exam exam) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) return;
    
    // 如果是学生用户，需要分配考试
    if (!_isAdmin) {
      // 在用户开始考试之前分配考试
      await ExamService.assignExamToStudent(exam.id, currentUser.id);
      }

    // 检查考试状态并执行相应操作
    ExamStateService.getExamStatus(exam.id, userId: currentUser.id).then((status) {
      setState(() {
        switch (status) {
          case ExamStatus.completed:
            // 已完成的考试显示结果
            _showCompletedExamDialog(exam);
            break;
            
          case ExamStatus.inProgress:
            // 如果考试进行中，询问是否继续
            showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: const Text('考试进行中'),
                content: const Text('检测到您有一个未完成的考试，是否继续?'),
                actions: [
                  TextButton(
                    onPressed: () {
                      Navigator.pop(context); // 关闭对话框
                    },
                    child: const Text('取消'),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context); // 关闭对话框
                      _resumeExam(exam);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: Text('继续考试'),
                  ),
                ],
              ),
            );
            break;
            
          case ExamStatus.notStarted:
            // 如果考试未开始，进入考试规则页面
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ExamRulesScreen(exam: exam),
              ),
            );
            break;
        }
      });
    });
  }
  
  // 显示已完成考试的对话框
  void _showCompletedExamDialog(Exam exam) async {
    // 获取当前用户
    final currentUser = UserData.currentUser;
    if (currentUser == null) return;
    
    // 获取考试结果
    final result = await ExamStateService.getExamResult(exam.id, currentUser.id);
    if (result == null) return;
    
    // 检查是否为管理员
    final isAdmin = await _authService.isUserAdmin();
    
    if (mounted) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(exam.title),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '您已完成此考试',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 16),
              _buildResultSummary(result, exam.totalScore),
              if (isAdmin) ...[
                const SizedBox(height: 16),
                Row(
                  children: [
                    Icon(Icons.admin_panel_settings, color: Colors.blue.shade800, size: 16),
                    const SizedBox(width: 8),
                    Text(
                      '管理员功能',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue.shade800
                      ),
                    ),
                  ],
                ),
              ],
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('关闭'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ResultScreen(
                      exam: exam,
                      result: result,
                      fromCompletedExam: true, // 标记为从已完成考试进入
                    ),
                  ),
                );
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
              child: Text('查看详情'),
            ),
            if (isAdmin)
              ElevatedButton(
                onPressed: () {
                  Navigator.pop(context);
                  _navigateToStudentResultsScreen(exam);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  foregroundColor: Colors.white,
                ),
                child: Text('学生答题记录'),
              ),
          ],
        ),
      );
    }
  }
  
  // 构建成绩摘要
  Widget _buildResultSummary(ExamResult result, int totalExamScore) {
    // final scorePercentage = (result.totalScore / totalExamScore * 100).toStringAsFixed(1);
    // final bool passed = result.totalScore >= (totalExamScore * 0.6);

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(
                Icons.assignment_turned_in,
                color: Colors.blue,
                size: 24,
              ),
              SizedBox(width: 8),
              Text(
                '考试已完成',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          // Text(
          //   '总分: ${result.totalScore}/${totalExamScore}',
          //   style: TextStyle(
          //     fontSize: 16,
          //     fontWeight: FontWeight.w500,
          //   ),
          // ),
          // Text(
          //   '得分率: $scorePercentage%',
          //   style: TextStyle(
          //     fontSize: 16,
          //     fontWeight: FontWeight.w500,
          //   ),
          // ),
          if (!result.isGraded)
            const Padding(
              padding: EdgeInsets.only(top: 8),
              child: Text(
                '* 主观题尚未评分完成',
                style: TextStyle(
                  fontSize: 14,
                  fontStyle: FontStyle.italic,
                  color: Colors.orange,
                ),
              ),
            ),
        ],
      ),
    );
  }
  
  // 恢复考试方法
  void _resumeExam(Exam exam) async {
    // 显示加载指示器
    setState(() {
      _isLoading = true;
    });
    
    // 获取考试状态
    final state = await ExamStateService.getCurrentUserExamState(exam.id);
    
    setState(() {
      _isLoading = false;
    });
    
    if (state == null) {
      // 如果没有找到状态（理论上不应该发生），作为新考试处理
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ExamRulesScreen(exam: exam),
        ),
      );
      return;
    }
    
    // 直接进入考试页面，传递初始状态
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ExamScreen(
          exam: exam,
          initialState: state,
        ),
      ),
    );
  }

  // 新增一个虚拟的importExcel方法
  void _importExcel() {
    // 显示选择对话框
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(
            '选择导入来源',
            style: ResponsiveUtil.getBalancedTextStyle(
              context,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.book, color: Colors.blue),
                title: Text(
                  '从内置试题导入',
                  style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 16),
                ),
                onTap: () {
                  Navigator.pop(context);
                  _importBuiltinExcel();
                },
              ),
              const Divider(),
              ListTile(
                leading: const Icon(Icons.folder, color: Colors.orange),
                title: Text(
                  '从固定路径导入',
                  style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 16),
                ),
                onTap: () {
                  Navigator.pop(context);
                  _importFixedPathExcel();
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              child: Text(
                '取消',
                style: ResponsiveUtil.getBalancedTextStyle(context, fontSize: 16),
              ),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
          ),
        );
      },
    );
  }
  
  // 添加缺少的方法
  void _downloadExcelTemplate() {
    _downloadTemplate(); // 复用现有方法
  }

  // 导入内置的Excel数据
  void _importBuiltinExcel() {
    setState(() {
      _isLoading = true;
    });
    
    ExamService.createExamFromExcel().then((exam) {
      if (exam != null) {
        _refreshExams();
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已成功导入内置试卷'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('导入内置试卷失败'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }).catchError((e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('导入内置试卷出错: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }).whenComplete(() {
      setState(() {
        _isLoading = false;
      });
    });
  }

  // 导入固定路径的Excel数据
  void _importFixedPathExcel() {
    setState(() {
      _isLoading = true;
    });
    
    ExamService.createExamFromFixedPathExcel().then((exam) {
      if (exam != null) {
        ExamService.addExam(exam);
        _refreshExams();
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已成功导入固定路径试卷'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('导入固定路径试卷失败'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }).catchError((e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('导入固定路径试卷出错: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }).whenComplete(() {
      setState(() {
        _isLoading = false;
      });
    });
  }

  // 添加 _generateTemplate 方法，作为 _generateFixedPathTemplate 的封装
  void _generateTemplate() {
    _generateFixedPathTemplate();
  }

  // 导航到学生答题记录页面
  void _navigateToStudentResultsScreen(Exam exam) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => StudentResultsScreen(exam: exam),
        settings: const RouteSettings(name: 'StudentResultsScreen'),
      ),
    );
  }

  Widget _buildStatusBadge(String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.bold,
          color: color,
        ),
      ),
    );
  }
} 